<template>
  <div class="app-container">
    <el-aside style="padding-right: 10px; padding-left: 15px; padding-top: 0px;float:left;width:20%;height:100%;background:none;">
      <div class="block" style="width:100%;height:100%;background-color: #FFF;">
        <el-cascader ref="cascaderHandle" v-model="xiangmuId" style="width:100%;" clearable :options="xmList" :props="optionProps" :show-all-levels="false" @change="change">
          <template slot-scope="{ data }">
            <span @click="clickNode">{{ data.xiangmumingcheng }}</span>
          </template>
        </el-cascader>
        <el-tree
          id="el-tree"
          ref="tree"
          class="filter-tree"
          :data="data2"
          node-key="id"
          :highlight-current="true"
          :props="defaultProps"
          :default-expanded-keys="TreeArr"
          :expand-on-click-node="false"
          @node-click="handleNodeClick"
        />
      </div>
    </el-aside>
    <el-aside style="padding-right: 5px; padding-left: 5px; padding-top: 0px;float:left;width:80%;background:none;">
      <div class="filter-container" style="margin-top:0px;padding-bottom: 0px;">
        <el-input v-model="queryPage.name" class="filter-item" placeholder="文档名称" style="width: 150px" clearable />
        <el-button class="filter-item" icon="el-icon-search" type="primary" @click="search()">查询</el-button>

        <el-button class="filter-item" icon="el-icon-upload" type="primary" @click="uploadFile()">上传</el-button>
      </div>

      <el-table v-show="displayVisible" v-loading="listLoading" :data="numList" :height="tableHeight5" style="width: 100%; overflow:auto;" border>
        <el-table-column type="index" header-align="center" align="center" label="序号" width="80px" />
        <el-table-column header-align="center" align="left" label="操作" width="320px" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="hlfp(scope)">查看</el-button>
          </template>
        </el-table-column>
        <el-table-column header-align="center" align="left" label="项目名称">
          <template slot-scope="scope">
            <span>{{ scope.row.xiangmuName }}</span>
          </template>
        </el-table-column>
        <el-table-column header-align="center" align="right" label="文档数量">
          <template slot-scope="scope">
            <span>{{ scope.row.num }}</span>
          </template>
        </el-table-column>
      </el-table>

      <el-table v-show="displayVisible1" v-loading="listLoading" :data="userList" :height="tableHeight5" border>
        <el-table-column type="index" align="center" label="序号" width="80px" />
        <el-table-column header-align="center" align="left" label="操作" width="260px" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="editFile(scope)">编辑</el-button>
            <el-button type="text" size="small" @click="download(scope)">下载</el-button>
            <el-button v-if="scope.row.isEdit === '2'" type="text" size="small" @click="remove(scope)">删除</el-button>
            <el-button type="text" size="small" @click="history(scope)">历史记录</el-button>
            <el-button type="text" size="small" @click="handleLog(scope)">日志</el-button>
          </template>
        </el-table-column>
        <el-table-column header-align="center" align="left" label="文档名" show-overflow-tooltip min-width="520px">
          <template slot-scope="scope">
            <span v-if="!['png','jpeg','jpg','pdf'].includes(scope.row.suffix)">{{ scope.row.originalName }}</span>
            <span v-else-if="['png','jpeg','jpg','pdf'].includes(scope.row.suffix)">
              <a style="color:#2878ff" target="_blank" @click="yulan(scope)" v-html="scope.row.originalName" />
            </span>
          </template>
        </el-table-column>
        <el-table-column header-align="center" align="left" label="标签" width="120" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ scope.row.fileLabel }}</span>
          </template>
        </el-table-column>
        <el-table-column header-align="center" align="left" label="文档类型" width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.suffix }}</span>
          </template>
        </el-table-column>
        <el-table-column header-align="center" align="left" label="目录" min-width="240px">
          <template slot-scope="scope">
            <span>{{ scope.row.xftName }}</span>
          </template>
        </el-table-column>
        <el-table-column header-align="center" align="right" label="版本号" min-width="120px">
          <template slot-scope="scope">
            <span>{{ scope.row.sortNum }}</span>
          </template>
        </el-table-column>
        <el-table-column header-align="center" align="left" label="创建人员" min-width="160px">
          <template slot-scope="scope">
            <span>{{ scope.row.createuserName }}</span>
          </template>
        </el-table-column>
        <el-table-column header-align="center" align="right" label="创建时间" min-width="180px">
          <template slot-scope="scope">
            {{ scope.row.createtimeTi }}
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="displayVisible1 && total>-1" :total="total" :page.sync="queryPage.page" :limit.sync="queryPage.limit" @pagination="loadList" />

      <el-dialog :visible.sync="addGroupVisible" append-to-body width="1000px" title="目录管理" :close-on-click-modal="false">
        <addGroup v-if="addGroupVisible" ref="addGroup" style="height:540px" :xiangmu="xiangmuId" :visible.sync="addGroupVisible" />
      </el-dialog>

      <el-dialog :visible.sync="uploadFileVisible" width="800px" append-to-body title="上传文件" :close-on-click-modal="false">
        <upload-file v-if="uploadFileVisible" ref="uploadFile" :link="linkId" :xiangmu="xiangmuId" :flag="flag" :visible.sync="uploadFileVisible" />
      </el-dialog>

      <el-dialog :visible.sync="editFileVisible" width="800px" append-to-body title="编辑" :close-on-click-modal="false">
        <edit-file v-if="editFileVisible" ref="editFile" :proid="code" :xiangmu="xiangmuId" :visible.sync="editFileVisible" />
      </el-dialog>

      <el-dialog :visible.sync="historyVisible" width="1200px" append-to-body title="历史记录" :close-on-click-modal="false">
        <history v-if="historyVisible" ref="history" :history="batchCode" :visible.sync="historyVisible" />
      </el-dialog>

      <el-dialog :visible.sync="historyLogVisible" width="1200px" append-to-body title="日志" :close-on-click-modal="false">
        <historyLog v-if="historyLogVisible" ref="historyLog" :history="batchCode" :visible.sync="historyLogVisible" />
      </el-dialog>

      <el-dialog :visible.sync="xmViewVisible" append-to-body width="640px" title="预览" :close-on-click-modal="false">
        <xm-view v-if="xmViewVisible" ref="xmView" :proid="code" :visible.sync="xmViewVisible" />
      </el-dialog>

      <el-dialog :visible.sync="viewPdfVisible" append-to-body width="1200px" title="预览" :close-on-click-modal="false">
        <view-pdf v-if="viewPdfVisible" ref="viewPdf" :proid="code" :visible.sync="viewPdfVisible" />
      </el-dialog>

      <el-dialog :visible.sync="viewModelVisible" width="800px" append-to-body title="编辑" :close-on-click-modal="false">
        <viewModel v-if="viewModelVisible" ref="viewModel" :proid="code" :xiangmu="xiangmuId" :visible.sync="viewModelVisible" />
      </el-dialog>

    </el-aside>
  </div>
</template>

<script>
import { getDictListByCode } from '@/api/dict'
import { getXiangMuList } from '@/api/projectInfo'
import { getList, getFileList, remove, downloadFile, saveRecords } from '@/api/projectFile'
import { getInitialLoading1, getAgainLoading1 } from '@/api/catalogDetail'
import { Message, MessageBox } from 'element-ui'
import { tableHeight5 } from '@/utils/tableHeight'
import Pagination from '@/components/Pagination'

import AddGroup from './addGroup'
import UploadFile from './uploadFile' // eslint-disable-line no-unused-vars
import EditFile from './uploadFile1' // eslint-disable-line no-unused-vars
import history from './history' // eslint-disable-line no-unused-vars
import XmView from './viewPhoto' // eslint-disable-line no-unused-vars
import ViewPdf from './viewPdf' // eslint-disable-line no-unused-vars
import historyLog from './historyLog' // eslint-disable-line no-unused-vars
import viewModel from './view' // eslint-disable-line no-unused-vars

export default {
  name: 'Zzjg',
  components: { Pagination, AddGroup, UploadFile, EditFile, history, XmView, ViewPdf, historyLog, viewModel },
  mixins: [tableHeight5],
  provide() {
    return {
      getList: this.onloadList
    }
  },
  data() {
    return {
      TreeArr: [],
      optionProps: {
        value: 'id',
        children: 'children',
        label: 'xiangmumingcheng',
        checkStrictly: false,
        expandTrigger: 'hover'
      },
      IdArr: [],
      listLoading: false,
      displayVisible: false,
      displayVisible1: false,
      total: 0,
      numList: [],
      userList: [],
      addGroupVisible: false,
      uploadFileVisible: false,
      editFileVisible: false,
      historyVisible: false,
      xmViewVisible: false,
      viewPdfVisible: false,
      historyLogVisible: false,
      xmList: [],
      data: [],
      data2: [],
      queryPage: {
        page: 1,
        limit: 20,
        name: ''
      },
      code: '',
      flag: '',
      batchCode: '',
      parent: '',
      parentId: '',
      parentName: '',
      xiangmuId: '',
      linkId: '',
      defaultProps: {
        children: 'children',
        label: 'typeName'
      },
      img1: require('../../../assets/images/Folder-01.png'),
      spTypes: [],
      viewModelVisible: false
    }
  },
  created() {
    this.getList()
    this.getXiangMuList()
    this.getDictEntry('YW_APPROVAL_STATE')
  },
  methods: {
    onloadList() {
      this.TreeArr = []
      this.IdArr = []

      this.getTreeList(this.xiangmuId)
      this.loadList()
    },
    getList() {
      this.displayVisible = true
      this.displayVisible1 = false
      getFileList().then(response => {
        this.numList = response.data
        this.listLoading = false
      }).catch(response => {
        this.listLoading = false
      })
    },
    // 提示框
    renderContent: function(h, { node, data, store }) {
      var text = data.typeName
      if (text.length > 15) {
        return (
          < span >
            < i > <img src={this.img1} style='width: 18px;height: 18px;margin-right:5px;padding-top:1px' /></i>
            <el-tooltip class='item' id='tool' effect='light' popper-class='draw' visible-arrow='false' content={data.typeName} placement='bottom-start' >
              <span class='style-demo' >{data.typeName}</span >
            </el-tooltip>
          </span>)
      } else {
        return (
          < span >
            < i > <img src={this.img1} style='width: 18px;height: 18px;margin-right:5px;padding-top:1px' /></i>
            <span class='style-demo' >{data.typeName}</span >
          </span>
        )
      }
    },
    hlfp(scope) {
      this.displayVisible = false
      this.displayVisible1 = true
      this.xiangmuId = scope.row.xiangmuId

      getInitialLoading1({ xiangmuId: scope.row.xiangmuId }).then(response => {
        this.data = response.data

        this.data2 = this.buildTree2(this.data)
        this.data2.forEach(m => {
          this.TreeArr.push(m.id)
        })

        this.listLoading = false
      }).catch(response => {
        this.listLoading = false
      })

      this.queryPage.type = scope.row.xftId
      this.queryPage.xiangmuId = scope.row.xiangmuId
      getList(this.queryPage).then(response => {
        const { data } = response

        this.userList = data.records
        this.total = parseInt(data.total)
        this.listLoading = false
      }).catch(response => {
        this.listLoading = false
      })
    },
    getDictEntry(code) {
      getDictListByCode(code).then(response => {
        if (code === 'YW_APPROVAL_STATE') {
          this.spTypes = response.data
        }
      })
    },
    getDicName(code, flag) {
      var dict = []
      if (flag === 'YW_APPROVAL_STATE') {
        dict = this.spTypes
        for (var i in dict) {
          if (dict[i].code === code) {
            return dict[i].name
          }
        }
      }
    },
    search() { // 查询
      this.displayVisible = false
      this.displayVisible1 = true

      this.loadList()
    },
    getXiangMuList() { // 加载列表
      this.xmList = []

      getXiangMuList(this.queryPage).then(response => {
        this.xmList = this.buildTree(response.data)

        this.listLoading = false
      }).catch(response => {
        this.listLoading = false
      })
    },
    buildTree(data) {
      var rdata = []
      for (let i = 0; i < data.length; i++) {
        var e1 = data[i]
        if (e1.parentId === '-1') {
          rdata.push(e1)
        }
        for (let j = 0; j < data.length; j++) {
          var e2 = data[j]
          if (e1.parentId === e2.id) {
            if (!e2.children) {
              e2.children = []
            }
            e2.children.push(e1)
          }
        }
      }
      return rdata
    },
    clickNode($event) {
      $event.target.parentElement.parentElement.firstElementChild.click()
      this.$refs.cascaderHandle.dropDownVisible = false
    },
    change(val) {
      const nodesObj = this.$refs['cascaderHandle'].getCheckedNodes()
      this.data = []
      this.data2 = []
      if (val.length === 2) {
        this.xiangmuId = nodesObj[0].data.id
        this.displayVisible = false
        this.getTreeList(nodesObj[0].data.id)
        this.displayVisible1 = true

        this.queryPage.xiangmuId = nodesObj[0].data.id
        getList(this.queryPage).then(response => {
          const { data } = response

          this.userList = data.records
          this.total = parseInt(data.total)
          this.listLoading = false
        }).catch(response => {
          this.listLoading = false
        })
      } else {
        this.displayVisible = true
        this.displayVisible1 = false
      }
    },
    getTreeList(code) { // 加载列表
      getInitialLoading1({ xiangmuId: code }).then(response => {
        this.data = response.data

        this.data2 = this.buildTree2(this.data)
        this.data2.forEach(m => {
          this.TreeArr.push(m.id)
        })

        this.listLoading = false
      }).catch(response => {
        this.listLoading = false
      })
    },
    buildTree2(data) {
      var rdata = []
      for (let i = 0; i < data.length; i++) {
        var e1 = data[i]
        if (e1.parentId === '1') {
          rdata.push(e1)
        }
        for (let j = 0; j < data.length; j++) {
          var e2 = data[j]
          if (e1.parentId === e2.id) {
            if (!e2.children) {
              e2.children = []
            }
            e2.children.push(e1)
          }
        }
      }
      return rdata
    },
    loadList(code) { // 加载列表
      this.listLoading = true
      this.queryPage.xiangmuId = this.xiangmuId

      getList(this.queryPage).then(response => {
        const { data } = response

        this.userList = data.records
        this.total = parseInt(data.total)

        this.listLoading = false
      }).catch(response => {
        this.listLoading = false
      })
    },
    handleAddGroup() {
      if (this.xiangmuId !== null && this.xiangmuId !== '') {
        this.addGroupVisible = true
        this.$nextTick(() => {
          this.$refs.addGroup
        })
      } else {
        Message({
          message: '请选择项目！',
          type: 'error',
          duration: 5 * 1000
        })
      }
    },
    handleNodeClick(data) {
      var dataA = data

      this.linkId = data.id
      this.parent = data.parentId

      if (!this.IdArr.includes(dataA.id)) {
        // 树
        getAgainLoading1({ parentId: dataA.id }).then(response => {
          if (!dataA.children) {
            this.$set(dataA, 'children', [])
            response.data.forEach(newChild => {
              dataA.children.push(newChild)
            })
            this.IdArr.push(dataA.id)
            this.dataId = dataA.id
          } else {
            return
          }

          this.listLoading = false
        }).catch(response => {
          this.listLoading = false
        })
      }

      this.queryPage.type = data.id
      this.queryPage.xiangmuId = this.xiangmuId
      getList(this.queryPage).then(response => {
        const { data } = response

        this.userList = data.records
        this.total = parseInt(data.total)

        this.listLoading = false
      }).catch(response => {
        this.listLoading = false
      })
    },
    uploadFile() {
      if (this.parent !== '-1') {
        if (this.xiangmuId !== null && this.xiangmuId !== '') {
          if (this.linkId !== null && this.linkId !== '') {
            this.uploadFileVisible = true
            this.$nextTick(() => {
              this.$refs.uploadFile
            })
          } else {
            Message({
              message: '请选择节点！',
              type: 'error',
              duration: 5 * 1000
            })
          }
        } else {
          Message({
            message: '请选择项目！',
            type: 'error',
            duration: 5 * 1000
          })
        }
      } else {
        Message({
          message: '请选择子节点！',
          type: 'error',
          duration: 5 * 1000
        })
      }
    },
    editFile(scope) {
      // this.editFileVisible = true
      // this.code = scope.row.id
      // this.$nextTick(() => {
      //   this.$refs.editFile
      // })
      this.viewModelVisible = true
      this.code = scope.row.id
      this.$nextTick(() => {
        this.$refs.viewModel
      })
    },
    history(scope) {
      this.historyVisible = true
      this.batchCode = scope.row.batchCode
      this.$nextTick(() => {
        this.$refs.history
      })
    },
    handleLog(scope) {
      this.historyLogVisible = true
      this.batchCode = scope.row.batchCode
      this.$nextTick(() => {
        this.$refs.historyLog
      })
    },
    yulan(scope) {
      saveRecords({ fileId: scope.row.id, flag: '1' }).then(response => {
      })
      if (['png', 'jpeg', 'jpg', 'PNG', 'JPEG', 'JPG'].includes(scope.row.suffix)) {
        this.xmViewVisible = true
        this.code = scope.row.id
        this.$nextTick(() => {
          this.$refs.xmView
        })
      } else if (['pdf', 'PDF'].includes(scope.row.suffix)) {
        this.viewPdfVisible = true
        this.code = scope.row.id
        this.$nextTick(() => {
          this.$refs.viewPdf
        })
      }
    },
    remove(scope) {
      MessageBox.confirm('确认删除', '确定', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '删除中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        remove({ code: scope.row.id }).then(response => {
          Message({
            message: '删除成功',
            type: 'success',
            duration: 5 * 1000
          })
          loading.close()
          this.getTreeList(this.xiangmuId)
          this.loadList()
        })
      })
    },
    download(scope) {
      const loading = this.$loading({
        lock: true,
        text: '下载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      downloadFile({ id: scope.row.id }).then(response => {
        var fileName = scope.row.originalName
        const contentDisposition = response.headers['content-disposition']
        if (contentDisposition) {
          fileName = window.decodeURI(response.headers['content-disposition'].split('=')[1], 'UTF-8')
        }
        const blob = new Blob([response.data], {
          type: `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet` // word文档为msword,pdf文档为pdf
        })
        const objectUrl = URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = objectUrl
        link.setAttribute('download', fileName)
        document.body.appendChild(link)
        link.click()
        // 释放内存
        window.URL.revokeObjectURL(link.href)

        saveRecords({ fileId: scope.row.id, flag: '2' }).then(response => {
        })
        loading.close()
      }).catch(response => {
        loading.close()
      })
    }
  }
}
</script>

<style lang="less" scoped>
.app-container{
  padding:10px 20px;
}
.filter-container {
  padding-bottom: 10px;

  .filter-item {
    display: inline-block;
    vertical-align: middle;
    margin-bottom: 10px;
    margin-right: 10px;
  }
  .date-filter-item{
    vertical-align: middle;
    margin-bottom: 10px;
    margin-right: 10px;
  }
  .box1 {
    flex: 1;
    vertical-align: middle;
    float: inline-start;
  }
  .box2 {
    flex: 1;
    text-align: end;
    float: inline-end;
  }
}
.pagination-container {
  margin-top: 0 !important;
  padding: 10px 16px !important;
}
</style>

<style scoped>

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
/* 右键会选中文字，为了美观将它禁用*/
#el-tree{
  user-select:none;
}
#el-tree >>> .style-demo {
  color: #474a4d;
  font-size: 14px;
  font-family: "黑体";
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}
.menu1 {
  /* height: 40px; */
  width: 120px;
  position: fixed;
  border: 1px solid #ccc;
  background-color: white;
  list-style: none;
  padding-left: 10px;
}
.menu2 {
  /* height: 100px; */
  width: 120px;
  position: fixed;
  border: 1px solid #ccc;
  background-color: white;
  list-style: none;
  padding-left: 10px;
}
.menu_item {
  line-height: 20px;
  text-align: left;
  margin-top: 10px;
}

</style>
